<?php
/**
 * CommentAction
 * 评论Action
 * @uses BaseAction
 * @package
 * @version $id$
 * @copyright 2009-2011 SamPeng
 * @author SamPeng <sampeng87@gmail.com>
 * @license PHP Version 5.2 {@link www.sampeng.cn}
 */
class CommentAction extends Action{
    const INDEX_TYPE_WEIBO = 0;
    const INDEX_TYPE_GROUP = 1;
    const INDEX_TYPE_ALL   = 2;
    	
    /**
     * getComment
     * 获取评论数据
     * @access public
     * @return void
     */
    public function getComment(){
    	$map['appid'] = intval($_REQUEST['appid']);
    	$map['type']  = t($_REQUEST['type']);
    	$map['toId']  = t($_REQUEST['id']);
     	$list = model('GlobalComment')->where($map)->order('id DESC')->findpage(10);
     	$appUid = $this->getInterFaceUid($map['type'], $map['appid']);
    	foreach ($list['data'] as $key=>$value){
    		$list['data'][$key]['uavatar'] = getUserSpace($value['uid'],'null','_blank','{uavatar}');
    		$list['data'][$key]['uspace'] = getUserSpace($value['uid'],'null','_blank','{uname}');
    		$list['data'][$key]['ctime'] = friendlyDate($value['cTime']);
    		$list['data'][$key]['comment'] = formatComment($value['comment']);
    		$list['data'][$key]['uname']   = getUserName($value['uid']);
    		$list['data'][$key]['del_state']   = ($appUid==$this->mid || $value['uid']==$this->mid)?1:0;
    		$list['data'][$key]['userGroupIcon']   = getUserGroupIcon($value['uid']);
    	}
    	
    	$_data['data'] = $list['data'];
    	$_data['appid'] = $map['appid'];
    	$_data['mid'] = $this->mid;
    	//exit(json_encode($list));
    	$html = W('comment', $_data,true);
    	$this->ajaxReturn($html);
    }
    
    // 快速回复
    public function quickReply() {
    	$_POST['to_id'] = intval($_POST['to_id']);
    	$this->assign('to_uname', getUserName(M('comment')->where('`id`='.$_POST['to_id'])->getField('uid')));
    	$this->assign('to_id', $_POST['to_id']);
    	$this->assign('callback', t($_POST['callback']));
    	$this->display();
    }
    
    public function doQuickReply() {
    	$_POST['to_id'] 	= intval($_POST['to_id']);
    	$_POST['comment']	= t(getShort($_POST['comment_content'], $GLOBALS['ts']['site']['length']));
    	if ( $_POST['to_id'] < 0 || empty($_POST['comment']) ) {
    		echo json_encode(array('data'=>array('reply_comment_id'=>0)));
    		return ;
    	}
    	$former_comment = M('comment')->where("`id`='{$_POST['to_id']}'")->find();
    	if ( empty($former_comment) ) {
    		echo json_encode(array('data'=>array('reply_comment_id'=>0)));
    		return ;
    	}

    	// 插入新数据
    	$data['type']	 = $former_comment['type']; // 应用名
    	$data['appid']	 = $former_comment['appid'];
    	$data['appuid']	 = $former_comment['author_uid'];
    	$data['uid']	 = $this->mid;
    	$data['comment'] = $_POST['comment'];
    	$data['cTime']	 = time();
    	$data['toId']	 = $former_comment['id'];
    	$data['status']	 = 0; // 0: 未读 1:已读
    	$data['quietly'] = $former_comment['quietly'];
    	$data['to_uid']	 = $former_comment['uid'];
    	$data['data']	 = $former_comment['data'];

    	$res = M('comment')->add($data);

    	if($res) {
    		// 应用回调: 增加应用的评论计数
    		$callback_data = unserialize($former_comment['data']);
    		$this->__doAddCallBack( $former_comment['appid'], $callback_data['table'], $callback_data['id_field'], $callback_data['comment_count_field'] );
    		//积分处理
			$setCredit = X('Credit');
			if($data['toId'] > 0 && $this->mid != $data['to_uid']){
				$setCredit->setUserCredit($this->mid,'reply_comment')
						  ->setUserCredit($data['to_uid'],'replied_comment');
			}else if($this->mid != $data['to_uid']){
				$setCredit->setUserCredit($this->mid,'add_comment')
				          ->setUserCredit($data['to_uid'],'is_commented');
			}
    		// 同时发一条微博
    		if ( intval($_POST['with_new_weibo']) ) {
    			$from_data = array('app_type'=>'local_app', 'app_name'=>$data['type'], 'title'=>$callback_data['title'], 'url'=>$callback_data['url']);
    			$from_data = serialize($from_data);
				D('Weibo','weibo')->publish($this->mid,
											array(
												'content' => html_entity_decode(
																$_POST['comment'] . ($_POST['to_id'] > 0?(' //@'.getUserName($former_comment['uid']) . ' :' . $former_comment['comment']):''),
																ENT_QUOTES
															 ),
											), 0, 0, '', '', $from_data);
    		}

    		echo json_encode(array('data' => array('reply_comment_id' => $_POST['to_id'])));
    	}else {
    		echo json_encode(array('data' => array('reply_comment_id' => 0)));
    	}
    }

    public function doAddComment() {
    	$_REQUEST['with_new_weibo']		= intval($_REQUEST['with_new_weibo']);
    	$_REQUEST['type']					= t($_REQUEST['type']);
    	$_REQUEST['appid']					= intval($_REQUEST['appid']);
    	$_REQUEST['comment']				= $_REQUEST['comment'];
    	$_REQUEST['to_id']					= intval($_REQUEST['to_id']);
    	$_REQUEST['author_uid']			= intval($_REQUEST['author_uid']);
    	$_REQUEST['title']					= t(html_entity_decode($_REQUEST['title'],ENT_QUOTES));
    	$_REQUEST['url']					= urldecode($_REQUEST['url']);
    	$_REQUEST['table']					= t($_REQUEST['table']);
    	$_REQUEST['id_field']				= t($_REQUEST['id_field']);
    	$_REQUEST['comment_count_field']	= t($_REQUEST['comment_count_field']);

        $app_alias	= getAppAlias($_REQUEST['type']);

    	// 被回复内容
    	$former_comment = array();
    	if ( $_REQUEST['to_id'] > 0 )
    		$former_comment = M('comment')->where("`id`='{$_REQUEST['to_id']}'")->find();

    	// 插入新数据
    	$map['type']	= $_REQUEST['type']; // 应用名
    	$map['appid']	= $_REQUEST['appid'];
    	$map['appuid']	= $_REQUEST['author_uid'];
    	$map['uid']		= $this->mid;
    	$map['comment']	= t(getShort($_REQUEST['comment'], $GLOBALS['ts']['site']['length']));
    	$map['cTime']	= time();
    	$map['toId']	= $_REQUEST['to_id'];
    	$map['status']	= 0; // 0: 未读 1:已读
    	$map['quietly']	= 0;
    	$map['to_uid']	= $former_comment['uid'] ? $former_comment['uid'] : $_REQUEST['author_uid'];
    	$map['data']	= array(
    									'table'					=> $_REQUEST['table'], 
    									'id_field'				=> $_REQUEST['id_field'], 
    									'comment_count_field'	=> $_REQUEST['comment_count_field'],
								);
    	$res = model('GlobalComment')->add($map);

    	// 避免命名冲突
    	unset($map['data']);

    	if ($res) {
    		// 应用回调: 增加应用的评论计数
    		$this->__doAddCallBack( $_REQUEST['appid'], $_REQUEST['table'], $_REQUEST['id_field'], $_REQUEST['comment_count_field'] );
    		//积分处理
			$setCredit = X('Credit');
			if($map['toId'] > 0 && $this->mid != $map['to_uid']){
				$setCredit->setUserCredit($this->mid,'reply_comment')
						  ->setUserCredit($map['to_uid'],'replied_comment');
			}else if($this->mid != $map['to_uid']){
				$setCredit->setUserCredit($this->mid,'add_comment')
				          ->setUserCredit($map['to_uid'],'is_commented');
			}
    		// 发表微博
    		if ($_REQUEST['with_new_weibo']) {
    			$from_data = array('app_type'=>'local_app', 'app_name'=>$_REQUEST['type'], 'title'=>$_REQUEST['title'], 'url'=>$_REQUEST['url']);
    			$from_data = serialize($from_data);
				D('Weibo','weibo')->publish($this->mid,
											array(
												'content' => html_entity_decode(
																 $_REQUEST['comment'] . ($_REQUEST['to_id'] > 0?(' //@' . getUserName($former_comment['uid']) . ' :' . $former_comment['comment']):''),
																 ENT_QUOTES
															 ),
											), 0, 0, '', '', $from_data);
    		}
/*        		
        	// 给被回复人发送通知
			if ($former_comment['uid']) {
				$data = array(
					'app_alias'	=> $app_alias,
					'url'		=> $_REQUEST['url'],
					'title'		=> $_REQUEST['title'],
					'content'	=> $_REQUEST['comment'],
					'my_content'=> $former_comment['comment'],
				);
				service('Notify')->send($former_comment['uid'], 'home_replyComment', $data, $this->mid);
				unset($data);
			}
			// 给作者发送通知 ( 当被回复人和作者为同一人时, 只发一个通知. 优先被回复. )
			if ($_REQUEST['author_uid'] > 0 && $_REQUEST['author_uid'] != $former_comment['uid']) {
				$data = array(
					'app_alias'	=> $app_alias,
					'url'		=> $_REQUEST['url'],
					'title'		=> $_REQUEST['title'],
					'content'	=> $_REQUEST['comment'],
				);
				service('Notify')->send($_REQUEST['author_uid'], 'home_addComment', $data, $this->mid);
				unset($data);
			}
*/
			
			// 组装结果集
			/*$result = $map;
			$result['data']['uavatar']  		= getUserSpace($this->mid,'null','_blank','{uavatar}');
			$result['data']['uspace']   		= getUserSpace($this->mid,'null','_blank','{uname}');
			//$result['data']['comment']  		= $_REQUEST['comment'];
			$result['data']['ctime']    		= L('just_now');
			$result['data']['uname']    		= getUserName($this->mid);
			$result['data']['comment']			= formatComment(t($_REQUEST['comment']));
			$result['data']['id']				= $res;
			$result['data']['userGroupIcon']	= getUserGroupIcon($this->mid);
			$result['data']['del_state']   		= 1;
            echo json_encode( $result );*/
			// remove cache
			D ( 'Operate', 'weibo' )->_removeWeiboCache($_REQUEST['to_id']);
			$str = '<div class="comment comment_line">
					' . getUserSpace($this->mid,'avatar','_blank','{uavatar}'). '
					<div class="article">
						<a href="' . U('home/Space/index', array('uid' => $this->mid)). '" class="author">' . getUserName($this->mid). '</a><span class="date"> (' .  L('just_now') . ')</span>
						<p>' .  formatComment(t($_REQUEST['comment'])) . '</p>
						<div class="buttons">
					';
			if (APP_NAME == 'ask') {
				$str .='			<a href="' .U('home/Comment/', array('id' => $res, 'type'=>$_REQUEST['type'])). '" class="ding button_r1">顶+11</a>
									<a href="' .U('home/Comment/doCai', array('id' => $res, 'type'=>$_REQUEST['type'])). '" class="cai button_r1">踩+11</a>
									<a href="' .U('home/Comment/doOK', array('id' => $res, 'type'=>$_REQUEST['type'])). '" class="ok button_o4">采纳</a>';				
			}

			$str .= '
								<a href="' .U('home/Comment/doDelete', array('id' => $res, 'type'=>$_REQUEST['type'])). '" class="delete button_r1">删除</a>
						</div>						
					</div>
				</div>';     
			$this->ajaxReturn($str); 
        }else{
            echo -1;
        }
    }
    
    public function doDelete() {
    	$_REQUEST['id'] = explode(',', t($_REQUEST['id']));
    	if ( empty($_REQUEST['id']) )
    		return ;
    	if(model('GlobalComment')->deleteComment($_REQUEST['id'])){	
    		//积分处理
			$setCredit = X('Credit');
			$setCredit->setUserCredit($this->mid,'delete_comment');
			// remove cache
			D ( 'Operate', 'weibo' )->_removeWeiboCache($_REQUEST['id']);
			// todo decrement master table count
			echo 1;
		}else{
			echo 0;
		}
    }
    
    // 评论成功后, 回调处理, 增加评论计数
    private function __doAddCallBack($appid, $table,$id_field = 'id', $comment_count_field = 'commentCount') {
    	return $table ? M($table)->setInc($comment_count_field, "`$id_field`='$appid'") : false;
    }
    
    private function getInterFaceUid($type,$intId){
    	 $info = M('blog')->where("type='{$type}' AND id={$intId}")->field('uid')->find();
    	 return $info['uid'];
    }
}
